/**
 * File: PropertyfileConfigResource.java
 * Created by: mhaimel
 * Created on: 30 Mar 2009
 * CVS:  $Id: PropertyfileConfigResource.java,v 1.1 2009/04/22 07:38:10 mhaimel Exp $
 */
package uk.ac.ebi.velvet.util.config.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.io.IOUtils;

import uk.ac.ebi.curtain.utils.io.impl.ClasspathIO;
import uk.ac.ebi.velvet.util.PathUtil;
import uk.ac.ebi.velvet.util.config.ConfigResource;
import uk.ac.ebi.velvet.util.io.ReadException;

/**
 * @author mhaimel
 *
 */
public class PropertyfileConfigResource implements ConfigResource {
	
	private static final String EXT_PROPERTIES = ".properties";

	public PropertyfileConfigResource() {
		// do nothing
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Properties getProperties(Class<?> clazz) {
		String propertyFilePath = getPropertyFilePath(clazz);
		Properties prop = new Properties();
		InputStream in = null;
		try {
			in = openStream(propertyFilePath);
			if(null != in){
				prop.load(in);
			}
		} catch (IOException e) {
			throw new ReadException(
					"Problems reading from property file" + propertyFilePath,e);
		} finally{
			IOUtils.closeQuietly(in);
		}
		return prop;
	}

	private InputStream openStream(String propertyFilePath)
			throws IOException {
		return new ClasspathIO(propertyFilePath).getInputStream();
	}
	
	private String getPropertyFilePath(Class<?> clazz){
		return PathUtil.getPath(clazz, clazz.getSimpleName()+EXT_PROPERTIES);
	}
}
